﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DialogMa
{

    private Dictionary<int, List<DialogData>> mDic = new Dictionary<int, List<DialogData>>();

    private DialogData mCurId;
    private List<DialogData> mCurDialogList;

    public void Init(List<DialogMeta> data)
    {
        List<DialogData> d = new List<DialogData>();
        foreach (var item in data)
        {
            d = new List<DialogData>();
            if (mDic.ContainsKey(item.GroupId))
            {
                var list = mDic[item.GroupId];

                for (int i = 0; i < list.Count; i++)
                {
                    if (list[i].DialogList[0].Id == item.Id)
                    {
                        list[i].DialogList.Add(item);
                        break;
                    }
                }
            }
            else
            {
                mDic.Add(item.GroupId, d);
                DialogData temp = new DialogData();
                temp.DialogList = new List<DialogMeta>();
                temp.DialogList.Add(item);
            }
        }

        //排序
        foreach (var item in mDic.Values)
        {
            foreach (var i in item)
            {
                if (i.DialogList != null)
                {
                    i.DialogList.Sort((x, y) =>
                    {
                        return x.Id - y.Id;
                    });
                }
            }
        }

    }


    public List<DialogData> GetAll(int guidId)
    {
        if (mDic.ContainsKey(guidId))
            return mDic[guidId];
        else
            return null;
    }

    public DialogData StartDialog(int guidId)
    {
        mCurId = null;
        mCurDialogList = mDic[guidId];
        return NextDialog();
    }

    public DialogData NextDialog(int select = 0)
    {
        if (mCurDialogList.Count == 0)
            return null;

        if (mCurId == null)
        {
            mCurId = mCurDialogList[0];
            return mCurId;
        }


        var meta = mCurId.DialogList[select];
        int nextId = meta.NextId;

        if (nextId == 0)
            return null;

        for (int i = 0; i < mCurDialogList.Count; i++)
        {
            if (mCurDialogList[i].Id == nextId)
            {
                mCurId = mCurDialogList[i];
                return mCurDialogList[i];
            }
        }
        return null;
    }

}

public class DialogMeta
{
    public int Id { get; set; }

    public int GroupId { get; set; }

    public string Head { get; set; }

    public string Text { get; set; }

    public int NextId { get; set; }

    public string Audio { get; set; }
}

public class DialogData
{
    public int Id { get; set; }
    public List<DialogMeta> DialogList { get; set; }

    public DialogData()
    {

    }
}
